<template>
  <view class="scan-container">
    <up-navbar :title="useT('扫一扫')" left-icon="arrow-left" bg-color="transparent" leftIconColor="#fff" titleColor="#fff" :autoBack="true"></up-navbar>
    <view class="scan-content">
      <view class="scan-icon">
        <text class="icon-text">📱</text>
      </view>
      <view class="scan-title">
        <text class="title-text">{{ useT('扫一扫') }}</text>
      </view>
      <view class="scan-desc">
        <text class="desc-text">{{ useT('点击下方按钮开始扫码') }}</text>
      </view>
    </view>

    <view class="scan-button-area">
      <button class="scan-button" @click="startScan">
        <text class="button-text">{{ useT('开始扫码') }}</text>
      </button>
    </view>

    <view class="result-modal" v-if="showResult">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">{{ useT('用户信息') }}</text>
        </view>
        <view class="modal-body">
          <view class="user-info-section" v-if="userInfo">
            <view class="user-avatar">
              <image class="avatar-image" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill" />
            </view>
            <view class="user-details">
              <text class="user-name">{{ userInfo.nickname || useT('未知用户') }}</text>
              <text class="user-phone" v-if="userInfo.phone">{{ useT('手机') }}: {{ maskPhone(userInfo.phone) }}</text>
              <text class="user-id">ID: {{ userInfo.uid || scanResult.userId }}</text>
              <text class="payment-amount" v-if="scanResult.amount">{{ useT('收款金额') }}: T{{ scanResult.amount }}</text>
            </view>
          </view>
          <view class="result-item">
            <text class="result-label">{{ useT('验证结果') }}:</text>
            <text class="result-value" :class="scanResult.valid ? 'valid' : 'invalid'">
              {{ scanResult.valid ? useT('验证通过') : useT('验证失败') }}
            </text>
          </view>
        </view>
        <view class="modal-footer">
          <button class="modal-button cancel" @click="closeResult">
            <text class="button-text">{{ useT('取消') }}</text>
          </button>
          <button class="modal-button confirm" @click="handlePayment" v-if="scanResult.valid">
            <text class="button-text">{{ useT('去付款') }}</text>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { getUserBaseInfo } from '@/api/user.js';
import { parsePaymentAddress } from '@/utils/crypto.js';
import { useT } from '@/utils/i18n.js';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';

// 响应式数据
const showResult = ref(false);
const scanResult = ref({
  original: '',
  decoded: '',
  valid: false,
  userId: ''
});
const userInfo = ref(null);

// 页面加载
onLoad(() => {
  console.log('扫一扫页面加载完成');
});

// 开始扫码
const startScan = () => {
  uni.scanCode({
    success: (res) => {
      handleScanResult(res.result);
    },
    fail: (err) => {
      console.error('扫码失败:', err);
      uni.showToast({
        title: useT('扫码失败'),
        icon: 'none'
      });
    }
  });
};

// 处理扫码结果
const handleScanResult = async (result) => {
  console.log('扫码结果:', result);

  const parseResult = parsePaymentAddress(result);
  console.log('parseResult', parseResult);

  scanResult.value = {
    original: result,
    decoded: parseResult.original,
    valid: parseResult.valid,
    userId: parseResult.userId,
    amount: parseResult.amount
  };

  if (parseResult.valid) {
    // 调用获取用户信息接口
    await getUserInfo(parseResult.userId);
  } else {
    uni.showToast({
      title: useT('请扫描正确的二维码'),
      icon: 'none'
    });
  }

  showResult.value = true;
};

// 获取用户信息
const getUserInfo = async (userId) => {
  try {
    const response = await getUserBaseInfo({ uid: userId });
    console.log('API响应:', response);

    if (response && response.data) {
      userInfo.value = {
        uid: response.data.uid || userId,
        phone: response.data.phone || '',
        nickname: response.data.nickname || useT('用户') + userId,
        avatar: response.data.avatar || '/static/default-avatar.png'
      };
    } else {
      // 如果API返回数据异常
      uni.showToast({
        title: response.msg || useT('获取用户信息失败'),
        icon: 'none'
      });
    }
    console.log('用户信息:', userInfo.value);
  } catch (error) {
    console.error('获取用户信息失败:', error);
    uni.showToast({
      title: error || error.message || useT('获取用户信息失败'),
      icon: 'none'
    });
  }
};

// 关闭结果弹窗
const closeResult = () => {
  showResult.value = false;
};

// 处理付款
const handlePayment = () => {
  if (scanResult.value.valid && scanResult.value.userId) {
    // 跳转到扫码付款页面，传递用户ID和金额
    const amountParam = scanResult.value.amount ? `&amount=${scanResult.value.amount}` : '';
    uni.navigateTo({
      url: `/pagesA/scan/payment?userId=${scanResult.value.userId}${amountParam}`
    });
    closeResult();
  }
};

// 手机号脱敏处理
const maskPhone = (phone) => {
  if (!phone || phone.length !== 11) {
    return phone;
  }
  // 显示前3位和后4位，中间用****代替
  return `${phone.substring(0, 3)}****${phone.substring(7)}`;
};
</script>

<style lang="scss" scoped>
.scan-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #12c284 0%, #8059ff 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.scan-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 100rpx;
}

.scan-icon {
  width: 200rpx;
  height: 200rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
}

.icon-text {
  font-size: 80rpx;
}

.scan-title {
  margin-bottom: 20rpx;
}

.title-text {
  color: #ffffff;
  font-size: 48rpx;
  font-weight: 600;
}

.scan-desc {
  text-align: center;
}

.desc-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 28rpx;
}

.scan-button-area {
  width: 100%;
  display: flex;
  justify-content: center;
}

.scan-button {
  background: #ffffff;
  border: none;
  border-radius: 50rpx;
  padding: 30rpx 80rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
  width: 80%;
}

.button-text {
  color: #12c284;
  font-size: 32rpx;
  font-weight: 600;
}

.result-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  background: #ffffff;
  border-radius: 20rpx;
  width: 80%;
  max-width: 600rpx;
  overflow: hidden;
}

.modal-header {
  background: #12c284;
  padding: 30rpx;
  text-align: center;
}

.modal-title {
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
}

.modal-body {
  padding: 30rpx;
}

.user-info-section {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20rpx;
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.user-details {
  flex: 1;
}

.user-name {
  display: block;
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
  margin-bottom: 8rpx;
}

.user-phone {
  display: block;
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 4rpx;
}

.user-id {
  display: block;
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 4rpx;
}

.payment-amount {
  display: block;
  font-size: 28rpx;
  color: #12c284;
  font-weight: 600;
}

.result-item {
  margin-bottom: 20rpx;
}

.result-label {
  display: block;
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 8rpx;
}

.result-value {
  display: block;
  font-size: 28rpx;
  color: #333333;
  word-break: break-all;
  line-height: 1.5;

  &.valid {
    color: #4caf50;
    font-weight: 600;
  }

  &.invalid {
    color: #f44336;
    font-weight: 600;
  }
}

.modal-footer {
  display: flex;
  border-top: 2rpx solid #e5e5e5;
}

.modal-button {
  flex: 1;
  border: none;
  padding: 24rpx;
  font-size: 28rpx;

  &.cancel {
    background: #f5f5f5;
    color: #666666;
    .button-text {
      color: #666666;
    }
  }

  &.confirm {
    background: #12c284;
    color: #ffffff;
    .button-text {
      color: #ffffff;
    }
  }
}
</style>
